package com.pms.service.impl;

import com.alibaba.excel.EasyExcel;
import com.pms.common.PageBean;
import com.pms.exception.BusinessException;
import com.pms.mapper.SysUserMapper;
import com.pms.pojo.SysUser;
import com.pms.service.SysUserService;
import io.micrometer.common.util.StringUtils;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public SysUser login(SysUser user) {
        String code = user.getCode();
        String password = user.getPassword();

        // 1. 根据用户名查询数据库中的数据
        SysUser sysUser = sysUserMapper.getByCodeWithDeptAndPost(code);
        // 2. 处理各种异常情况(用户名不存在、密码不对、账号被锁定)
        if (sysUser == null) {
            throw new RuntimeException("用户名不存在");
        }
        // 检查 passwordHash 是否为 null
        if (sysUser.getPassword() == null) {
            throw new RuntimeException("用户密码未设置");
        }
        // 密码比对
        if (!sysUser.getPassword().equals(password)) {
            throw new RuntimeException("密码错误");
        }
        if (sysUser.getStatus() == 1) {
            throw new RuntimeException("账号被锁定");
        }
        // 3. 清除密码信息后返回
        sysUser.setPassword(null);
        return sysUser;
    }



    @Override
    public void updatePassword(Long userId, String oldPassword, String newPassword) {
        // 1. 查询用户
        SysUser user = this.getById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 2. 验证旧密码 - 直接比较明文密码
        if (!user.getPassword().equals(oldPassword)) {
            throw new RuntimeException("原密码错误");
        }

        // 3. 更新新密码 - 直接使用明文密码
        user.setPassword(newPassword);
        this.update(user);
    }

    /**
     * 保存用户
     *
     * @param sysUser
     */
    @Override
    public void save(SysUser sysUser) {
        // 检查工号是否已存在
        if (sysUserMapper.checkCodeExists(sysUser.getCode(), null) > 0) {
            throw new BusinessException("工号已存在");
        }

        // 密码加密
//        String password = DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes());
//        sysUser.setPassword(password);

        sysUserMapper.insert(sysUser);
    }

    /**
     * 更新用户信息
     *
     * @param sysUser
     */
    @Override
    public void update(SysUser sysUser) {
        // 检查工号是否已存在
        if (sysUserMapper.checkCodeExists(sysUser.getCode(), sysUser.getId()) > 0) {
            throw new BusinessException("工号已存在");
        }

        // 如果密码不为空，则需要加密
        if (StringUtils.isNotEmpty(sysUser.getPassword())) {
//            String password = DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes());
//            sysUser.setPassword(password);
        }

        sysUserMapper.update(sysUser);
    }

    /**
     * 删除用户
     *
     * @param id
     */
    @Override
    public void delete(Long id) {
        sysUserMapper.deleteById(id);
    }

    /**
     * 根据 id 查询用户
     *
     * @param id
     * @return
     */
    @Override
    public SysUser getById(Long id) {
        return sysUserMapper.getById(id);
    }

    /**
     * 更新用户状态
     *
     * @param id
     * @param status
     */
    @Override
    public void updateStatus(Long id, Integer status) {
        sysUserMapper.updateStatus(id, status);
    }

    /**
     * 查询所有
     *
     * @return
     */
    @Override
    public List<SysUser> list() {
        return sysUserMapper.list();
    }

    @Override
    public PageBean<SysUser> page(Integer page, Integer pageSize, String code, String name,
                                  Long deptId, Long postId, Integer status) {
        // 计算起始索引
        Integer start = (page - 1) * pageSize;

        // 查询总记录数
        Long total = sysUserMapper.count(code, name, deptId, postId, status);

        // 查询当前页数据
        List<SysUser> records = sysUserMapper.page(start, pageSize, code, name, deptId, postId, status);

        // 使用建造者模式创建PageBean
        return PageBean.<SysUser>builder()
                .total(total)
                .rows(records)  // 注意这里使用 rows 而不是 records
                .build();
    }

    @Override
    public List<SysUser> findByIds(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return new ArrayList<>();
        }
        return sysUserMapper.selectByIds(ids);
    }

    @Override
    public void batchDelete(List<Long> ids) {
        sysUserMapper.batchDelete(ids);
    }

    @Override
    public void export(HttpServletResponse response) throws Exception {
        // 查询所有员工数据
        List<SysUser> list = this.list();

        // 创建Excel文件
        EasyExcel.write(response.getOutputStream(), SysUser.class)
                .sheet("员工信息")
                .doWrite(list);

        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=employee_list.xlsx");
    }

    /**
     * 根据用户ID查询用户详细信息
     * @param userId
     * @return
     */
    @Override
    public SysUser getUserDetailInfo(Long userId) {
        SysUser user = sysUserMapper.getUserDetailInfo(userId);
        if (user != null) {
            // 出于安全考虑，清除密码信息
            user.setPassword(null);
            // 处理一些特殊字段的格式化或转换（如果需要的话）
        }
        return user;
    }


}
